﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;

namespace BusinessIntelligenceToolkit.Framework.Extensions
{
    public static class ListCollectionViewExtensions
    {
        public static IList<object> GetItems(this ListCollectionView listCollectionView, object item, int count)
        {
            int currentItemIndex = 0;
            int currentIndex = 0;
            bool found = false;

            List<object> result = new List<object>();
            int addedCount = 0;
            foreach (object each in listCollectionView.SourceCollection)
            {
                if (each.Equals(item))
                {
                    currentItemIndex = currentIndex;
                    found = true;
                }

                if (found && addedCount < count)
                {
                    addedCount++;
                    result.Add(each);
                }

                currentIndex++;
            }

            if (addedCount != count)
            {
                var needToAddCount = count - addedCount;
                int indexToStart = (currentItemIndex - needToAddCount) <= 0 ? 0 : currentItemIndex - needToAddCount;
                for (int i = currentItemIndex - 1; i >= indexToStart; i--)
                {
                    addedCount++;
                    result.Insert(0, listCollectionView.SourceCollection.Cast<object>().ToList()[i]);
                }
            }

            return result;
        }

        public static IList<object> GetItems(this ListCollectionView listCollectionView, int position, int count)
        {
            int indexToStart = position;
            int indexToEnd = position + count;
            
            List<object> result = new List<object>();
            List<object> sourceCollectionList = listCollectionView.SourceCollection.Cast<object>().ToList();
            if (indexToEnd > sourceCollectionList.Count)
            {
                var start = indexToStart - (indexToEnd - sourceCollectionList.Count);
                indexToStart = start < 0 ? 0 : start;
                indexToEnd = sourceCollectionList.Count;
            }

            for (int i = indexToStart; i < indexToEnd; i++)
            {
                result.Add(sourceCollectionList[i]);
            }

            return result;
        }

        public static IEnumerable<object> GetItemsAt(this ListCollectionView listCollectionView, int[] indexes)
        {
            return indexes.Select(index => listCollectionView.GetItemAt(index));
        }

        public static void SetCurrentItem(this ListCollectionView listCollectionView, object item)
        {
            listCollectionView.MoveCurrentToPosition(listCollectionView.IndexOf(item));
        }
    }
}